package com.pazl.check.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pazl.check.enums.ReturnCodeEnum;
import com.pazl.check.utils.MessageUtil;  
 
/**
 * 全局校验异常处理
 *
 */
@ControllerAdvice  
//如果返回的为json数据或其它对象，添加该注解  
@ResponseBody  
public class GlobalExceptionHandler {  
    //添加全局异常处理流程，根据需要设置需要处理的异常，本文以MethodArgumentNotValidException为例  
    @ExceptionHandler(value=MethodArgumentNotValidException.class)  
    public Object methodArgumentNotValidHandler(HttpServletRequest request,  
            MethodArgumentNotValidException exception) throws Exception {  
        //按需重新封装需要返回的错误信息  
    	StringBuilder builder = new StringBuilder();
        //解析原错误信息，封装后返回，此处返回非法的字段名称，原始值，错误信息  
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {  
            builder.append(error.getDefaultMessage()+"\n ");
        }  
        return MessageUtil.buildDto(ReturnCodeEnum.UNVALID, builder.toString());
    }  
}  